package handlers

import (
	"errors"
	"net/http"
	"strconv"

	"qimo_work/models"
	"qimo_work/repositories"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// GetAllCommentsHandler 获取指定文章的所有评论（支持分页）
func GetAllCommentsHandler(c *gin.Context) {
	postID, err := strconv.Atoi(c.Param("post_id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的文章 ID"})
		return
	}

	page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err != nil || page < 1 {
		page = 1
	}

	pageSize, err := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	if err != nil || pageSize < 1 {
		pageSize = 10
	}

	comments, total, err := repositories.GetCommentsByPostID(uint(postID), page, pageSize)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取评论列表失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"data":     comments,
		"total":    total,
		"page":     page,
		"pageSize": pageSize,
	})
}

// GetCommentHandler 获取单个评论
func GetCommentHandler(c *gin.Context) {
	commentID, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的评论 ID"})
		return
	}

	comment, err := repositories.GetCommentByID(uint(commentID))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取评论失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": comment})
}
func AddCommentHandler(c *gin.Context) {
	// 从上下文中获取 userID
	userID, exists := c.Get("userID")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "用户未登录"})
		return
	}

	// 直接断言为 uint
	userIDUint, ok := userID.(uint)
	if !ok {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "用户 ID 类型错误"})
		return
	}

	var input struct {
		PostID   uint   `json:"post_id"`
		Content  string `json:"content"`
		ParentID *uint  `json:"parent_id"` // 可选的父评论 ID
	}
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据", "details": err.Error()})
		return
	}

	// 验证 ParentID 是否存在并合法
	if input.ParentID != nil {
		parentComment, err := repositories.GetCommentByID(*input.ParentID)
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				c.JSON(http.StatusBadRequest, gin.H{"error": "父评论不存在"})
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": "验证父评论时出错", "details": err.Error()})
			}
			return
		}

		if parentComment.PostID != input.PostID {
			c.JSON(http.StatusBadRequest, gin.H{"error": "父评论不属于当前文章"})
			return
		}
	}

	// 创建评论
	comment := models.Comment{
		PostID:   input.PostID,
		UserID:   userIDUint,
		Content:  input.Content,
		ParentID: input.ParentID,
	}

	// 插入评论
	if err := repositories.AddComment(&comment); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "添加评论失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "评论添加成功", "data": comment})
}

// DeleteCommentHandler 删除评论
func DeleteCommentHandler(c *gin.Context) {
	commentID, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的评论 ID"})
		return
	}

	if err := repositories.DeleteComment(uint(commentID)); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除评论失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "评论已删除"})
}

// UpdateCommentHandler 更新评论
func UpdateCommentHandler(c *gin.Context) {
	commentID, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的评论 ID"})
		return
	}

	var comment models.Comment
	if err := c.ShouldBindJSON(&comment); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据", "details": err.Error()})
		return
	}

	comment.ID = uint(commentID)

	if err := repositories.UpdateComment(&comment); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新评论失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "评论更新成功", "data": comment})
}
